package com.lepu.datajackson.fastjson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.lepu.datajackson.annotation.SensitiveInfo;
import com.lepu.datajackson.config.SensitiveStrategy;
import com.lepu.datajackson.vo.SimpleVo;


import java.lang.reflect.Field;

/**
 * 脱敏过滤器
 *
 * @author yongqiang.guo
 * @date 2021/11/3
 */
public class SensitiveValueFilter implements ValueFilter {
    @Override
    public Object process(Object object, String name, Object value) {
        try {
            Field field = object.getClass().getDeclaredField(name);
            SensitiveInfo annotation = field.getAnnotation(SensitiveInfo.class);
            if (annotation != null) {
                SensitiveStrategy strategy = annotation.value();
                if (strategy != null && value instanceof String) {
                    return strategy.desensitizer().apply((String) value);
                }
            }
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return value;
    }


    public static void main(String[] args) {
        SimpleVo simpleVo = new SimpleVo();
        simpleVo.setPhone("19233339488");
        simpleVo.setIdNo("513436200011039734");
//        simpleVo.setIdNo(null);
        simpleVo.setEmail("yongqiang.guo@lepudigital.com");
        simpleVo.setUserName(null);
        String s = JSON.toJSONString(simpleVo, new SensitiveValueFilter());
        System.out.println(s);
    }
}
